package org.example.controller;

import org.example.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/seckill")
public class SeckillController {
    @Autowired
    private SeckillService seckillService;

    /**
     * 初始化商品库存
     */
    @PostMapping("/init/{productId}")
    public String initStock(@PathVariable String productId, @RequestParam int stock) {
        seckillService.initProductStock(productId, stock);
        return "商品" + productId + "库存初始化成功，库存数量：" + stock;
    }

    /**
     * 执行秒杀
     */
    @PostMapping("/do/{productId}")
    public SeckillService.SeckillResult doSeckill(
            @PathVariable String productId,
            @RequestParam(defaultValue = "1") int quantity) {
        return seckillService.doSeckill(productId, quantity);
    }

    /**
     * 查询商品库存
     */
    @GetMapping("/stock/{productId}")
    public String getStock(@PathVariable String productId) {
        Integer stock = seckillService.getProductStock(productId);
        if (stock != null) {
            return "商品" + productId + "当前库存：" + stock;
        } else {
            return "商品不存在";
        }
    }
}
